/**
 * 
 */
package com.owen.he.jee.dao.impl.ibatis;

/**
 * com.tiancom.pas.framework.ibatis.dialect <br>
 * 说明：orcel 数据库方言实现<br>
 * <br>
 * 
 * @author: meteor 创建时间 2007-3-21 上午11:02:24
 */
public class OrcaleDialect implements Dialect {

	protected static final String SQL_END_DELIMITER = ";";

	public String getLimitString(String sql, boolean hasOffset) {
		return new StringBuffer(sql.length() + 20).append(trim(sql)).append(
				hasOffset ? " limit ?,?" : " limit ?")
				.append(SQL_END_DELIMITER).toString();
	}

	public String getLimitString(String sql, int starRow, int pageSize) {
		if (starRow < 0) {
			throw new UnsupportedOperationException("sql server has no offset");
		}
		int rows = pageSize + starRow;
		StringBuffer newSql = new StringBuffer();
		newSql.append(" select * from ( ");
		newSql.append(" 	select r.*, rownum rn from ( ");
		newSql.append(		sql);
		//newSql.append(" )r ");
		//newSql.append(" )pg ");
		newSql.append(" 	)r where rownum<="+rows);
		newSql.append(" )pg where pg.rn>="+(starRow));
		//newSql.append(" where pg.rn> " + starRow + " and ");
		//newSql.append(" pg.rn <" + (rows+1) + " "); 
		return newSql.toString();
	}
	
	


	/**
	 * 
	 * @param sql
	 * @return
	 */
	static int getAfterSelectInsertPoint(String sql) {
		int selectIndex = sql.toLowerCase().indexOf("select");
		final int selectDistinctIndex = sql.toLowerCase().indexOf(
				"select distinct");
		return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6);
	}

	static int getAfterUnionSelectInsertPoint(StringBuffer sql) {
		String newSql = sql.toString();
		int selectIndex = newSql.toLowerCase().indexOf("union select");
		if (selectIndex != -1) {
			return selectIndex + 13;
		} else {
			return -1;
		}
	}

	public boolean supportsLimit() {
		return true;
	}

	private String trim(String sql) {
		sql = sql.trim();
		if (sql.endsWith(SQL_END_DELIMITER)) {
			sql = sql.substring(0, sql.length() - 1
					- SQL_END_DELIMITER.length());
		}
		return sql;
	}
}